<?php defined('BASEPATH') || exit('No direct script access allowed');

use EasyWeChat\Foundation\Application;
use EasyWeChat\Core\AccessToken;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Image;

class Wechat extends Front_Controller
{
    private $_token = 'usuretech_mh';
    private $_logFile = '/mnt/data/www/udianfang/application/logs/easywechat.log';
    // private $_logFile = '/Users/zhenwenliu/Documents/usuretech/udianfang/application/logs/easywechat.log';

	public function __construct()
	{
		parent::__construct();
	}

    public function service() {
        $options = [
            'debug'  => true,
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
            'token'  => $this->_token,
            // 'aes_key' => null, // 可选
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
            //...
        ];
        $app = new Application($options);
        $server = $app->server;
        $user = $app->user;
        $oauth = $app->oauth;

        $server->setMessageHandler(function ($message) use ($user) {
            $text = '空空';
            if ($message->MsgType) {
                $text = $this->{$message->MsgType}($message, $user);
            }
            return $text;
        });
        $response = $server->serve();
        // 将响应输出
        $response->send();
    }

    // 处理微信、消息 开始
    private function event($message, $user) {
        $text = $message->Event.' ===';
        // 事件消息...
        if ($message->Event == 'subscribe') {
            $fromUser = $user->get($message->FromUserName);
            $code = $this->subscribe($fromUser);
            // $text = $fromUser->nickname.' 你好，欢迎关注 优向科技! 你的唯一识别码是：'.$code;
            $text = "您的登录授权码是：".$code."，请妥善保管好！\n想知道如何调戏溪溪，请回复\"怎么用\" \n免费试用请回复\"1\"";
            $text = "嘿～很高兴你终于来了。灵溪找客，为地产人量身定制的找客工具。\n\n基于优向科技数据实践所沉淀的『潜在购房人群库』，准确匹配目标客户，只为你投放最精准的地产广告～\n\n<a href='".base_url()."/mohe/account'>立即领取1000元投放体验金</a>";
        } elseif ($message->Event == 'unsubscribe') {
            $fromUser = $user->get($message->FromUserName);
            $this->unsubscribe($fromUser);
        } elseif ($message->Event == 'VIEW') {
            // $this->load->helper('string');
            // $code = random_string('alnum', 8);
            // $fromUser = $user->get($message->FromUserName);
            // $this->subscribe($fromUser, $code);
            $text = 'view';
        }
        return $text;
    }
    private function text($message, $user) {
        if ($message->Content == '怎么用') {
            $news = new News();
            $news->title = '灵溪程序化投放-从入门到精通';
            $news->description = '灵溪营销工具颠覆了传统“创意设计、媒体商务洽谈、投放总结”的营销流程，将繁杂的人工环节和议价环节省去，整合在一个微信服务号中，让你用最快的速度争夺到潜在客户。本文将带你快速了解灵溪程序化投放的操作方法。';
            $news->image = 'https://mmbiz.qlogo.cn/mmbiz_png/iaj42QQkpjRTfPFG68ITiaGYicW5tABwRaeibRH8ibE6anpIVGR8cRABtE5KeVQgYdqFPO2FlocooaC2KPvOD6HIv0Q/0?wx_fmt=png';
            $news->url = 'http://mp.weixin.qq.com/s?__biz=MzI3ODQ2NDAzMg==&mid=2247483667&idx=1&sn=4c78763a6c3df5f696e83d5cdedd35d7&chksm=eb57d25cdc205b4a661719d4bea0351fab27777564456a72e1db7518ea62ea20cc662d7c0bd2#rd';
            return $news;
        } else if ($message->Content == '1') {
            $text = new Image();
            $text->media_id = 'G2vFt0-uG3bW5Tm0kPFGyjPn-GKJ1j8buCRjiEcMpe4';
            return $text;
        }
        return 'text tap';
    }
    private function image($message, $user) {
        return 'image tap';
    }
    private function voice($message, $user) {
        return 'voice tap';
    }
    private function video($message, $user) {
        return 'video tap';
    }
    private function location($message, $user) {
        return 'location tap';
    }
    private function link($message, $user) {
        return 'link tap';
    }
    // 处理微信、消息 结束


    public function createMenu() {
        $options = [
            'debug'  => true,
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
            'token'  => $this->_token,
            // 'aes_key' => null, // 可选
            'log' => [
                'level' => 'debug',
                'file'  => $this->_logFile, // XXX: 绝对路径！！！！
            ],
            //...
        ];
        $app = new Application($options);
        $domain = "http://enft1.free.natapp.cc/mohe";
        $domain = "http://udfang.com/mohe";
        $buttons = [
            [
                "name"       => "免费投放",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "新建楼盘",
                        "url"  => $domain."/produce"
                    ],
                    [
                        "type" => "view",
                        "name" => "充值",
                        "url"  => $domain."/charge/",
                    ],
                    
                ]
            ],
            [
                "name"       => "数据报告",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "投放效果",
                        "url"  => $domain."/report"
                    ],
                    [
                        "type" => "view",
                        "name" => "销售线索",
                        "url"  => $domain."/phone",
                    ],
                    
                ]
            ],
            [
                "type" => "view",
                "name" => "我的账户",
                "url" => $domain."/account"
            ]
        ];
        $buttons = [
            [
                "name"       => "我",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "关于我们",
                        "url"  => $domain."/about"
                    ],
                    [
                        "type" => "view",
                        "name" => "客源列表",
                        "url"  => $domain."/phone",
                    ],
                    [
                        "type" => "view",
                        "name" => "我的账户",
                        "url"  => $domain."/account",
                    ],
                ]
            ],
            [
                "type" => "view",
                "name" => "去找客!",
                "url" => $domain."/zhaoke"
            ],
            [
                "type" => "view",
                "name" => "购买",
                "url" => $domain."/charge/"
            ]
        ];
        $app->menu->add($buttons);
    }

    // 关注账号
    private function subscribe($fromUser) {
        $this->load->model('wechat/wechatusers_model');
        return $this->wechatusers_model->subscribe($fromUser);
    }
    // 取消关注账号
    private function unsubscribe($fromUser) {
        $this->load->model('wechat/wechatusers_model');
        $this->wechatusers_model->unsubscribe($fromUser);
    }
    
    public function token() {
        $accessToken = new AccessToken(config_item("wechat.app_id"), config_item("wechat.app_secret"));
        $token = $accessToken->getToken(); // token 字符串
        dump($token).PHP_EOL;
    }


    public function notice(){

        //初始化微信sdk 
        $options = [
            // 前面的appid什么的也得保留哦
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
            'payment' => config_item("wechat.payment"),
        ];
        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号transaction_id" 或者 "商户订单号out_trade_no" 去自己的数据库找到订单
            $this->load->model('mohe/mhpay_model');
            $order = $this->mhpay_model->find($notify->out_trade_no); //此处使用商户订单号查询订单
            if (!$order) { // 如果订单不存在
                return 'Order not exist.';
            }
            // 检查订单是否已经更新过支付状态
            if ($order->status == 1) {
                return true; // 已经支付成功了就不再更新了
            }
            //写入数据库
            $this->load->model('wechat/mhwxorder_model');
            $orderData = array(
                    'appid'=>isset($notify->appid) && !empty($notify->appid) ? $notify->appid : '',
                    'mch_id'=>isset($notify->mch_id) && !empty($notify->mch_id) ? $notify->mch_id : '',
                    'nonce_str'=>isset($notify->nonce_str) && !empty($notify->nonce_str) ? $notify->nonce_str : '',
                    'sign'=>isset($notify->sign) && !empty($notify->sign) ? $notify->sign : '',
                    'result_code'=>isset($notify->result_code) && !empty($notify->result_code) ? $notify->result_code : '',
                    'err_code'=>isset($notify->err_code) && !empty($notify->err_code) ? $notify->err_code : '',
                    'err_code_des'=>isset($notify->err_code_des) && !empty($notify->err_code_des) ? $notify->err_code_des : '',
                    'openid'=>isset($notify->openid) && !empty($notify->openid) ? $notify->openid : '',
                    'is_subscribe'=>isset($notify->is_subscribe) && !empty($notify->is_subscribe) ? $notify->is_subscribe : '',
                    'trade_type'=>isset($notify->trade_type) && !empty($notify->trade_type) ? $notify->trade_type : '',
                    'bank_type'=>isset($notify->bank_type) && !empty($notify->bank_type) ? $notify->bank_type : '',
                    'total_fee'=>isset($notify->total_fee) && !empty($notify->total_fee) ? $notify->total_fee : 0,
                    'fee_type'=>isset($notify->fee_type) && !empty($notify->fee_type) ? $notify->fee_type : '',
                    'cash_fee'=>isset($notify->cash_fee) && !empty($notify->cash_fee) ? $notify->cash_fee : 0,
                    'transaction_id'=>isset($notify->transaction_id) && !empty($notify->transaction_id) ? $notify->transaction_id : '',
                    'out_trade_no'=>isset($notify->out_trade_no) && !empty($notify->out_trade_no) ? $notify->out_trade_no : 0,
                    'time_end'=>isset($notify->time_end) && !empty($notify->time_end) ? $notify->time_end : '',
                );
            $wxOrderId = $this->mhwxorder_model->insert($orderData);
            // 用户是否支付成功
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $result = $this->mhpay_model->update($notify->out_trade_no,['status'=>1]); 
                if($result){
                    $this->load->model('wechat/wechatusers_model');
                    //将金额充值到个人账户
                    $userData = $this->wechatusers_model->find_by(['openid'=>$notify->openid]);
                    $res = $this->wechatusers_model->update(['id'=>$userData->id],['credit'=>$userData->credit+$order->credit_back]);
                }
            } else { // 用户支付失败
                $result = $this->mhpay_model->update($notify->out_trade_no,['status'=>2]);
            }
            return true; // 返回处理完成
        });
        // 将响应输出
        $response->send();
    }

}
/* end ./application/controllers/Wechat.php */
